﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Xml;
using System.Net;
using System.Text;
using System.IO;

/// <summary>
/// ClsInterface 的摘要?明
/// </summary>
public class ClsInterface
{
    private string ApiUrl, api_key, xmlPath, sMessage, AppID;
    private string Status;
    private XmlDocument xmlDoc;

    // 初始化
    public ClsInterface(string filePath)
    {
        IniConfig(filePath);

        xmlDoc = new XmlDocument();
        try
        {
            xmlDoc.Load(xmlPath);
        }
        catch
        {
            xmlDoc.LoadXml("<?xml version=\"1.0\" encoding=\"gb2312\"?><root/>");
        }

        SetValue("appid", AppID, 0);
    }

    private void IniConfig(string filePath)
    {
        Cls_Config cfg = new Cls_Config(filePath);
        //Response.Write("==>" + cfg["SYSKEY"]);

        // ????文件
        ApiUrl = cfg["URLS"];//"http://bbs.SalePartial.com/api/1.0/dv_api_serv.aspx";

        // 安全?
        api_key = cfg["SYSKEY"];//"DvSalePartial";

        // ?求的XML格式文件     
        xmlPath = cfg["FORMAT"];//"http://bbs.SalePartial.com/api/1.0/pdo.user.xml"; //System.Web.HttpContext.Current.Server.MapPath("../api/1.0/pdo.user.xml");

        // 返回提示
        sMessage = "";

        // 返回状????
        Status = "1";

        // ?求整合方名称
        AppID = cfg["APPID"];//"dvbbs";
    }

    /// <summary>
    /// 更新?料
    /// </summary>
    public void UpdateUser(string name, string password, string answer, string email, string question, string truename, string info, string userface, string sex)
    {
        SetValue("action", "update", 0);
        SetValue("syskey", MD5(name + api_key, 32), 0);
        SetValue("username", name, 1);
        SetValue("password", password, 0);
        SetValue("email", email, 1);

        if (answer != null)
        {
            SetValue("answer", answer, 1);
        }
        if (question != null)
        {
            SetValue("question", question, 1);
        }

        //性?反置，如不修改?留空
        if (sex == "0")
        {
            sex = "1";
        }
        else
        {
            if (sex == "1")
                sex = "0";
            else
                sex = "";
        }
        SetValue("gender", sex, 0);

        string[] infoarr = info.Split('	');
        if (infoarr != null && infoarr.Length >= 6)        // homepage, qq, msn, telephone, mobile, address
        {
            SetValue("homepage", infoarr[0], 1);
            SetValue("qq", infoarr[1], 0);
            SetValue("msn", infoarr[2], 1);
            SetValue("telephone", infoarr[3], 0);
            SetValue("mobile", infoarr[4], 0);
            SetValue("address", infoarr[5], 0);
        }

        SetValue("truename", truename, 0);
        SendHttpData();
    }


    /// <summary>
    /// 更新?料
    /// </summary>
    public void UpdatePassword(string name, string password)
    {
        SetValue("action", "update", 0);
        SetValue("syskey", MD5(name + api_key, 32), 0);
        SetValue("username", name, 1);
        SetValue("password", password, 1);

        SendHttpData();
    }
    
    /// <summary>
    /// ?除一个或多个用?
    /// </summary>
    /// <param name="names">用?名，多个?以 “,” 分割</param>
    public void DeleteUsers(string names)
    {
        SetValue("action", "delete", 0);   

        //将用?名前后用来分隔的?引号去掉，?保留逗号?分隔符。一次可?除多个用?
        string[] name = names.Split(',');
        for (int i = 0; i < name.Length; i++)
        {
            names = names.Replace("'", "");
            SetValue("username", names, 1);
            SetValue("syskey", MD5(name + api_key, 32), 0);
            SendHttpData();

            if (Status == "1")
            {
                System.Web.HttpContext.Current.Response.Write(sMessage);
            }
        }
    }

    /// <summary>
    /// ??用?是否存在，在注册新用?将数据写到数据?之前，需要?用此函数?行判断
    /// 此?未?送用?的?件地址，如果要求?件地址不能重?，可?送?接口?行??
    /// </summary>
    /// <param name="username">用?名</param>
    public void CheckName(string username)
    {
        SetValue("action", "checkname", 0);
        SetValue("username", username, 1);
        SetValue("syskey", MD5(username + api_key,32), 0);
        SendHttpData();

        if (Status == "1")
        {
            System.Web.HttpContext.Current.Response.Write(sMessage);
        }
    }

    /// <summary>
    /// 向接口程序?求?取用?信息，返回?型可以不是void，而是集合或数?
    /// 如果Dvbbs不需要使用?方面的功能，?此函数可以不写
    /// </summary>
    public void RegUser(string name, string password, int experience, int money, string sex, string email, string face, string question, string answer, string truename, string info, string signature, string firstid, string lastip, int logins, bool isactivated, string referrer)
    {
        SetValue("action", "reguser", 0);
        SetValue("syskey", MD5(name + api_key,32), 0);
        SetValue("username", name, 1);
        SetValue("password", password, 0);
        SetValue("email", email, 0);
        SetValue("question", question, 1);
        SetValue("answer", answer, 1);
        
        if (sex == "0") // Dvbbs性??置与其他程序相反，0?男性，1?女性
          sex = "1";
        else
          sex = "0";
        SetValue("gender", sex, 0);

        string[] infoarr = info.Split('	');
        // homepage, qq, msn, telephone, mobile, address
        if (infoarr != null && infoarr.Length >= 6)
        {
            SetValue("homepage", infoarr[0], 1);
            SetValue("qq", infoarr[1], 0);
            SetValue("msn", infoarr[2], 1);
            SetValue("telephone", infoarr[3], 0);
            SetValue("mobile", infoarr[4], 0);
            SetValue("address", infoarr[5], 1);
        }
        SetValue("userip", lastip, 0);
        SetValue("experience", experience.ToString(), 0);
        SetValue("ticket", money.ToString(), 0);

        int t = 0;
        if (!isactivated)
        {
            t = 4;
        }
        SetValue("userstatus", t.ToString(), 0);
        SetValue("truename", truename, 0);
        SendHttpData();

        if (Status == "1")
        {
            //在此??行?除已注册用?操作 
            //Dvbbs.Data.Connection conn = new Dvbbs.Data.Connection();
            //conn.Execute("delete from " + Fetch.TablePrefix + "user where username='" + Text.SqlEncode(name) + "'");

            System.Web.HttpContext.Current.Response.Write("?用?已被注册!");
        }
    }

    // 登?
    public void Login(string userName, string password, string toUrl)
    {
        System.Web.HttpContext.Current.Response.Write("<script type=\"text/javascript\">function Href() {location.href=\"" + toUrl + "\"} ;</script><iframe src=\""
            + ApiUrl + "?syskey=" + MD5(userName + api_key, 32) + "&username=" + Str2Hex(userName) + "&password=" + Str2Hex(password) 
            + "&savecookie=0\" width=\"0\" height=\"0\" style=\"display:none\" onload=\"Href();\"></iframe>");
    }

    //注?
    public void LogOut(string userName, string toUrl)
    {
        System.Web.HttpContext.Current.Response.Write("<script type=\"text/javascript\">function Href() {location.href=\"" + toUrl + "\"} ;</script><iframe src=\""
            + ApiUrl + "?syskey=" + MD5(userName + api_key, 32) + "&username=" + Str2Hex(userName) + "&password=" 
            + "&savecookie=0\" width=\"0\" height=\"0\" style=\"display:none\" onload=\"Href();\"></iframe>");
    }


    // ?造指定格式的xml数据
    public void SetValue(string name, string value, int type)
    {
        name = name.ToLower();
        XmlNode node = xmlDoc.DocumentElement.SelectSingleNode(name);

        if (node == null)
        {
            node = xmlDoc.DocumentElement.AppendChild(xmlDoc.CreateNode("element", name, ""));
        }

        if (type == 1)
        {
            node.InnerText = "";
            node.AppendChild(xmlDoc.CreateCDataSection(value.Replace("]]>", "]]&gt;")));
        }
        else
        {
            node.InnerText = value;
        }
    }

    // 从指定格式的xml中按?点?取?
    public string GetValue(string name)
    {
        XmlNode node = xmlDoc.DocumentElement.SelectSingleNode(name);
        if (node != null)
        {
          return node.InnerText;
        }

        return "null";
    }

    // ?送一个???求
    public void SendHttpData()
    {
        XmlDocument xml = new XmlDocument();
        string url = ApiUrl;

        if (url == "") return;

        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        string sendData = xmlDoc.InnerXml;
        byte[] byteArray = Encoding.Default.GetBytes(sendData);
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        WebResponse response = request.GetResponse();
        dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream, System.Text.Encoding.GetEncoding("GB2312"));
        string responseXml = reader.ReadToEnd();

        try
        {
            xml.LoadXml(responseXml);
            //	xml.Save(Fetch.MapPath("returndata.xml"));
            string appid = xml.DocumentElement.SelectSingleNode("appid").InnerText;
            string status = xml.DocumentElement.SelectSingleNode("status").InnerText;
            string message = xml.DocumentElement.SelectSingleNode("body/message").InnerText;
            Status = status;
            sMessage = message + "(" + appid + "提示)";
            if (status == "1")
            {
                return;
            }
        }
        catch
        {
            sMessage = "?求数据??！";
            return;
        }
        
        //System.Web.HttpContext.Current.Response.Write(sMessage);
    }


    private string MD5(string str, int length)
    {
        string result = "";
        if (length == 16) //16位MD5加密（取32位加密的9~25字符） 
        {
            result = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16);
        }

        if (length == 32) //32位加密 
        {
            result = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
        }

        return result;
    }

    // 密?提交前??
    public string Str2Hex(string s)
    {
        string result = string.Empty;
        byte[] arrByte = System.Text.Encoding.GetEncoding("GB2312").GetBytes(s);
    
        for (int i = 0; i < arrByte.Length; i++)
        {
            result += "%" + System.Convert.ToString(arrByte[i], 16); //Convert.ToString(byte, 16)把byte?化成十六?制string 
        }

        return result;
    } 
}
